package com.dehui.traders.ui.home;

import android.content.Context;
import android.text.TextUtils;

import com.dehui.traders.bean.BaseListResponse;
import com.dehui.traders.bean.IndexInfo;
import com.dehui.traders.bean.OptionalCode;
import com.dehui.traders.bean.OptionalCodeRank;
import com.dehui.traders.bean.RealtimeQuote;
import com.dehui.traders.bean.StockMinuteResponse;
import com.dehui.traders.bean.Tick;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.kchart.DataParse;
import com.dehui.traders.kchart.MyCombinedChartX;
import com.dehui.traders.kchart.PriceManager;
import com.dehui.traders.kchart.XVolumeManager;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.ui.optioanl.AddOptionalStockActivity;
import com.dehui.traders.ui.main.MainActivity;
import com.dehui.traders.ui.buysell.BuySellFragment;
import com.dehui.traders.ui.freightspace.FreightSpaceFragment;
import com.dehui.traders.ui.optioanl.OptionalStockManagerFragment;
import com.dehui.traders.ui.strategy.SmartChooseStocksFragment;
import com.dehui.traders.ui.trend.TrendFragment;
import com.dehui.traders.ui.OptionHelper;
import com.dehui.traders.utils.UserHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.KLog;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hqq on 18.3.29.
 */

public class HomeViewModel extends BaseViewModel{

    private HomeFragment home;
    private boolean isRreshingTodayTicks = false;
    private float preclose;
    private String code;
    private String name;
    private MyCombinedChartX mChartPrice;

    public BindingCommand trendOnClickCommand = new BindingCommand(()->{
        startContainerActivity(TrendFragment.class.getCanonicalName());
    });

    public BindingCommand chooseStocksOnClickCommand = new BindingCommand(()->{

        if (UserHelp.getIsLogin(context))
            startContainerActivity(SmartChooseStocksFragment.class.getCanonicalName());
    });

    public BindingCommand buySellOnClickCommand = new BindingCommand(()->{
        if (UserHelp.getIsLogin(context))
            startContainerActivity(BuySellFragment.class.getCanonicalName());
    });

    public BindingCommand positionsOnClickCommand = new BindingCommand(()->{
        startContainerActivity(FreightSpaceFragment.class.getCanonicalName());
    });

    public BindingCommand addOptionalStockOnClickCommand = new BindingCommand(()->{
        AddOptionalStockActivity.start(home.getActivity());
    });

    private DataParse mData;
    private Timer timer;
    private List<OptionalCode> optionalCodes = new ArrayList<>();

    public BindingCommand managerOptionalStockOnClickCommand = new BindingCommand(()->{
        if (UserHelp.getIsLogin(context)) {
            startContainerActivity(OptionalStockManagerFragment.class.getCanonicalName());
        }
    });
    private MyCombinedChartX mChartVolume;

    public HomeViewModel(Context context, HomeFragment home) {
        super(context);
        this.home = home;
    }

    public void initChartMinite(List<Tick> list) {
        if (mData == null)
            mData = new DataParse();
        mData.parseMinuteList(list,preclose);
        PriceManager.getInstange().initPrice(context,mChartPrice,mData,false);
        XVolumeManager.getInstange().initVolume(context,mChartVolume,mData,false);
    }

    public void initChartView(MyCombinedChartX mChartPrice, MyCombinedChartX mChartVolume) {
        if (mData == null)
            mData = new DataParse();
        this.mChartVolume = mChartVolume;
        this.mChartPrice = mChartPrice;
        PriceManager.getInstange().initPrice(context,mChartPrice,mData,false);
        XVolumeManager.getInstange().initVolume(context,mChartVolume,mData,false);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getCacheRealTimeQuotes();
        getRealTimeQuotes();
        getCacheOptionRealTimeQuotes();
    }

    private void getCacheRealTimeQuotes() {
        List<IndexInfo> list = OptionHelper.getHomeZhishu(context);
        if (list != null)
            home.refreshRealTimeQuotesList(list,true);
    }

    private void getCacheOptionRealTimeQuotes() {
        List<RealtimeQuote> list = OptionHelper.getCacheOptionRealTime(context);
        if (list != null)
            home.updataList(list);
    }


    private void getOptionalCodeByPhone() {
        if(TextUtils.isEmpty(Preferences.getToken()))
            return;

        String myOpitonCode = Preferences.getMyOpitonCode();
        try {
            List<OptionalCodeRank> codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
            optionalCodes.clear();
            for (OptionalCodeRank item : codeList){
                optionalCodes.add(new OptionalCode(item.code,item.status,item.name,item.market));
            }
            searchRealTime(codeList);
            getCodeByNet();
        }catch (Exception e){
            getCodeByNet();
        }

    }

    private void getCodeByNet() {
        NetImpl.getOptionalByPhone(UserHelp.getUserId())
                .enqueue(new CallListener<BaseListResponse<OptionalCode>>() {
                    @Override
                    public void _onResponse(Response<BaseListResponse<OptionalCode>> response) {
                        BaseListResponse<OptionalCode> optionalCodeBaseListResponse = response.body();
                        int status = optionalCodeBaseListResponse.status;
                        if(status == 200){
                            optionalCodes = optionalCodeBaseListResponse.result;
                            if (optionalCodes == null || optionalCodes.size() <= 0)
                                return;

                            //判断和本地缓存是否相同
                            if (OptionHelper.isCodeSame(optionalCodes)){
                                KLog.i("Hqq","缓存相同");
                                return;
                            }
                            KLog.i("Hqq","缓存不相同");
                            List<OptionalCodeRank> codeRanks = new ArrayList<>();
                            for (int i = 0; i < optionalCodes.size(); i++){
                                OptionalCode optionalCode = optionalCodes.get(i);
                                String code = optionalCode.getCode();
                                OptionalCodeRank codeRank = new OptionalCodeRank(optionalCode.getName(),code,optionalCode.getMarket(),optionalCode.getStatus());
                                codeRanks.add(codeRank);
                            }

                            String codestr = new Gson().toJson(codeRanks);
                            Preferences.saveMyOpitonCode(codestr);

                            searchRealTime(codeRanks);

                        }
                    }

                    @Override
                    public void _onFailure() {

                    }
                });
    }




    private void searchRealTime(List<OptionalCodeRank> list) {
        Call<BaseListResponse<RealtimeQuote>> call = NetImpl.getRealtimeQuote(list);
        call.enqueue(new CallListener<BaseListResponse<RealtimeQuote>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<RealtimeQuote>> response) {
                BaseListResponse<RealtimeQuote> realtimeQuoteBaseListResponse = response.body();
                if (realtimeQuoteBaseListResponse.status == 200){
                    List<RealtimeQuote> realtimeQuoteList = realtimeQuoteBaseListResponse.result;
                    home.updataList(realtimeQuoteList);
                    OptionHelper.saveRealTimeQuote(context,realtimeQuoteList);
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    private void getRealTimeQuotes() {
        Call<BaseListResponse<IndexInfo>> call = NetImpl.realtimeQuotes("0");
        call.enqueue(new CallListener<BaseListResponse<IndexInfo>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<IndexInfo>> response) {
                BaseListResponse<IndexInfo> indexInfoBaseResponse = response.body();
                int status = indexInfoBaseResponse.status;
                if(status == 200){
                    List<IndexInfo> list = indexInfoBaseResponse.result;
                    home.refreshRealTimeQuotesList(list,false);
                    OptionHelper.saveHomeZhishu(context,new Gson().toJson(list));
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void getTodayTicks(float preclose, String code, String name) {
        this.preclose = preclose;
        this.code = code;
        this.name = name;
        stopTimer();
        if (MainActivity.isRepeat){
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    if(!isRreshingTodayTicks && MainActivity.isRepeat && HomeFragment.isHomeVisity){
                        getTicks();
                    }

                }
            }, 0, 30 * 1000);
        }else{
            getTicks();
        }
    }

    private void getTicks() {
        isRreshingTodayTicks = true;
        Call<StockMinuteResponse> call = NetImpl.getTodayTicks1(code);
        call.enqueue(new CallListener<StockMinuteResponse>() {
            @Override
            public void _onResponse(Response<StockMinuteResponse> response) {
                isRreshingTodayTicks = false;
                StockMinuteResponse stockMinuteResponse = response.body();
                List<Tick> tickList = stockMinuteResponse.result;
                initChartMinite(tickList);
            }

            @Override
            public void _onFailure() {
                isRreshingTodayTicks = false;
            }
        });

    }

    private void stopTimer(){
        if( timer != null){
            timer.cancel();
            timer = null;
        }
    }

    public void refreshOptionData() {
        getOptionalCodeByPhone();
    }

    public String getMarket(int position) {
        return optionalCodes.get(position).getMarket();
    }
}
